//
// Created by hsj on 2022/2/24.
//

#include "t_exception.h"
namespace t_exception_test{
    //测试异常
    void test(){
            //不抛异常，失败时候返回空指针【c++11】
            int *ip = new (std::nothrow)int;
            if (ip == NULL){
                cout<<"malloa fail,back NULL pointer."<<endl;
            }

            double x,y,z;
            cout<<"Enter two numbers please."<<endl;
            while (cin >>x >> y){
                try {
                    z = hmean(x,y);
                    cout<<"You enter x="<<x<<" y="<<y<<"; result is z="<<z<<endl;
                }
//                catch (BadHMean &bhm){//使用引用，可以多态的使用
//                   cout<<bhm.message();//此处的bhm是hmean函数里面的BadHMean对象的副本的引用，因为hmean执行完成后BadHMean对象将不会存在。
//                   cout<<"Try again please."<<endl;
//                   continue;
//                }
//                catch (const char *cp){//默认的一种情况
//                    cout<<cp<<endl;
//                    cout<<"Try again please."<<endl;
//                    continue;
//                }
                catch(exception &e){
                    //处理任何异常
                    cout<<e.what()<<endl;
                    cout<<"catch exception and sub exception."<<endl;
                    continue;
                }
                catch(...){
                    //处理任何异常
                    cout<<"catch any exception."<<endl;
                    continue;
                }
            }
    }

    double hmean(double a,double b){
        if (a == -b){
            throw BadHMean(a,b);
        }
        return 2.0 * a * b / (a + b);
    }
}